{% extends "./student_base.html" %}

{% block page_title %}AI病人列表标准{% endblock %}

{% block main_content %}
<div class="container mt-4">
    <h2 class="text-center fw-bold">{{ title }}</h2>
    <p class="text-center text-text-secondary mb-6">选择左下方AI病人，进行诊疗练习</p>
    
    <!-- AI聊天区域 -->
    <div id="chat-container" class="flex-grow flex flex-col">
        <div class="border-b pb-2 mb-4">
            <h3 class="text-xl font-semibold" id="current-patient-title">正在诊疗: <span></span></h3>
        </div>
        
        <!-- 聊天消息区域 -->
        <div id="message-area" class="flex-grow overflow-y-auto border rounded-lg p-4 mb-4 bg-neutral/50" style="min-height: 400px;">
            <!-- 消息将通过JS动态添加 -->
        </div>
        
        <div class="flex gap-2">
            <input type="text" id="message-input" class="flex-grow px-4 py-2 border border-neutral-dark rounded-lg focus:outline-none focus:ring-2 focus:ring-primary/50" placeholder="">
            <button id="send-message" class="btn btn-primary px-6">发送</button>
        </div>
    </div>
</div>
{% endblock %}

{% block extra_js %}
<script>
$(document).ready(function() {
    // 存储当前选中的病人ID
    let currentPatientId = null;
    let eventSource = null;
    
    // 病人选择事件
    $('.patient-item').click(function() {
        // 更新选中状态
        $('.patient-item').removeClass('selected');
        $(this).addClass('selected');
        
        // 获取病人信息
        currentPatientId = $(this).data('patient-id');
        const patientCode = $(this).data('patient-code');
        const patientType = $(this).data('patient-type');
        
        // 更新标题并显示聊天区域
        $('#current-patient-title span').text(`${patientCode} (${patientType})`);
        $('#chat-container').removeClass('hidden');
        
        // 清空消息区域
        $('#message-area').html('');
        
        // 设置输入框默认文字
        $('#message-input').val('你好，你有哪里不舒服？');
        
        // 滚动到底部
        scrollToBottom();
    });
    
    // 发送消息
    $('#send-message').click(sendMessage);
    $('#message-input').keypress(function(e) {
        if (e.which === 13) { // 回车键发送
            sendMessage();
        }
    });
    
    // 发送消息函数
    function sendMessage() {
        if (!currentPatientId) {
            alert('请先选择一个AI病人');
            return;
        }
        
        const message = $('#message-input').val().trim();
        if (!message) return;
        
        // 添加用户消息到聊天区域
        const userMessageHtml = `
            <div class="flex mb-4 justify-end">
                <div class="bg-primary text-white p-3 rounded-lg rounded-tr-none max-w-[80%]">
                    ${message}
                </div>
                <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary ml-2">
                    <i class="fa fa-user"></i>
                </div>
            </div>
        `;
        $('#message-area').append(userMessageHtml);
        
        // 清空输入框
        $('#message-input').val('');
        
        // 滚动到底部
        scrollToBottom();
        
        // 显示AI正在输入状态
        const loadingHtml = `
            <div class="flex mb-4 ai-loading">
                <div class="w-8 h-8 rounded-full bg-primary/10 flex items-center justify-center text-primary mr-2">
                    <i class="fa fa-user-md"></i>
                </div>
                <div class="bg-primary/10 p-3 rounded-lg rounded-tl-none max-w-[80%]">
                    <div class="animate-pulse">正在输入...</div>
                </div>
            </div>
        `;
        $('#message-area').append(loadingHtml);
        scrollToBottom();
        
        // 调用AI API获取回复（流式）
        getAIStreamingResponse(currentPatientId, message);
    }
    
    // 获取AI流式回复
    function getAIStreamingResponse(patientId, message) {
        // 如果有活跃的连接，先关闭
        if (eventSource) {
            eventSource.close();
        }
        
        // 创建FormData
        const formData = new FormData();
        formData.append('patient_id', patientId);
        formData.append('message', message);
        formData.append('csrfmiddlewaretoken', '{{ csrf_token }}');
        
        // 创建临时ID用于标识当前AI回复
        const tempId = 'ai-response-' + Date.now();
        
        // 初始化AI回复容器
        $('.ai-loading').last().attr('id', tempId);
        
        // 使用Fetch API处理流式响应
        fetch("{% url 'get_ai_response' %}", {
            method: 'POST',
            body: formData,
        })
        .then(response => {
            if (!response.ok) {
                throw new Error('网络响应不正常');
            }
            
            const reader = response.body.getReader();
            const decoder = new TextDecoder();
            let aiResponse = '';
            
            // 处理流式数据
            function processText({ done, value }) {
                if (done) {
                    return;
                }
                
                // 解码接收到的内容
                const chunk = decoder.decode(value, { stream: true });
                const lines = chunk.split('\n\n');
                
                lines.forEach(line => {
                    if (line.startsWith('data:')) {
                        try {
                            const data = JSON.parse(line.slice(5).trim());
                            
                            if (data.type === 'delta' && data.content) {
                                // 更新AI回复内容
                                aiResponse += data.content;
                                $(`#${tempId}`).html(`
                                    <div class="bg-primary/10 p-3 rounded-lg rounded-tl-none max-w-[80%]">
                                        ${aiResponse}
                                    </div>
                                `);
                                scrollToBottom();
                            } 
                            else if (data.type === 'complete') {
                                // 完成回复，移除加载状态类
                                $(`#${tempId}`).removeClass('ai-loading');
                                console.log('AI回复完成:', data);
                            }
                            else if (data.type === 'error') {
                                $(`#${tempId}`).html(`
                                    <div class="bg-red-100 p-3 rounded-lg rounded-tl-none max-w-[80%] text-red-700">
                                        错误: ${data.message}
                                    </div>
                                `);
                            }
                        } catch (e) {
                            console.error('解析流式数据错误:', e);
                        }
                    }
                });
                
                return reader.read().then(processText);
            }
            
            return reader.read().then(processText);
        })
        .catch(error => {
            console.error('获取AI回复错误:', error);
            $(`#${tempId}`).html(`
                <div class="bg-red-100 p-3 rounded-lg rounded-tl-none max-w-[80%] text-red-700">
                    无法获取回复，请稍后再试。
                </div>
            `);
        });
    }
    
    // 滚动到消息底部
    function scrollToBottom() {
        const messageArea = document.getElementById('message-area');
        messageArea.scrollTop = messageArea.scrollHeight;
    }
});
</script>
{% endblock %}